package org.jetnuke.modules.admin.stories;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.jforum.ActionServletRequest;
import net.jforum.JForumExecutionContext;
import net.jforum.util.preferences.ConfigKeys;
import net.jforum.util.preferences.SystemGlobals;

import net.jforum.util.legacy.commons.fileupload.FileItem;
import org.apache.velocity.VelocityContext;
import org.jetnuke.common.ActionForward;
import org.jetnuke.common.IAction;
import org.jetnuke.common.IAdminInfo;
import org.jetnuke.common.IModuleInfo;
import org.jetnuke.common.IUserInfo;
import org.jetnuke.servlets.utilities.StringUtils;
import org.jetnuke.util.JetUtil;

public class UploadNewsFile implements IAction {

	public ActionForward exec(HttpServletRequest request,
			HttpServletResponse response, VelocityContext vc, IModuleInfo info,
			String op, IUserInfo ui, IAdminInfo ai) throws Exception {
		if(ai==null || ai.IsSuperUser()==false)
			return null;
		
		ActionServletRequest asr=JForumExecutionContext.getRequest();
		FileItem file=(FileItem)asr.getObjectParameter("file");
		
		BufferedInputStream inputStream = new BufferedInputStream(file.getInputStream());
		
		String realName = file.getName();
		String simplifiedName=StringUtils.getSimpleFileName(realName);
		String dir=SystemGlobals.getValue(ConfigKeys.ATTACHMENTS_STORE_DIR) + "/news/";
		new File(dir).mkdirs();
		
		File f = new File(dir,simplifiedName);
		OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(f));
		byte[] b = new byte[2048];
		while ((inputStream.read(b)) != -1) {
			outputStream.write(b);
		}
		
		outputStream.flush();
		outputStream.close();
		inputStream.close();
		JetUtil.redirect(vc,response,request.getContextPath()+"/do/admin/uploaded");
		return null;
	}

}
